package com.flying.fish.manage.filter;

import com.alibaba.fastjson.JSONObject;
import com.flying.fish.formwork.util.ApiResult;
import com.flying.fish.formwork.util.Constants;
import com.flying.fish.formwork.util.HttpResponseUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: maran
 * 描述   :
 * 公司   :
 * 创建人 : 马然
 * 时间   : 2021/7/14 21:15
 */
@Component
public class LoginFilter implements WebFilter {

    /**
     * 白名单（不需要登录也能访问的接口）
     */
    public static List<String> whitelist = new ArrayList<>();

    static {
        // 初始化白名单
        whitelist.add("/login");
    }

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        if (whitelist.contains(request.getURI().getPath())) {
            return chain.filter(exchange);
        }
        if (!isLogin(request)){
            return HttpResponseUtils.write(exchange.getResponse(), HttpStatus.OK, JSONObject.toJSONString(new ApiResult(Constants.NOT_LOGIN)));
        }
        return chain.filter(exchange);
    }

    public boolean isLogin(ServerHttpRequest request) {
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isBlank(token) || redisTemplate.opsForValue().get("TOKEN:" + token) == null) {
            return false;
        }
        return true;
    }
}
